import axios from "axios";
import store from '@/store'
import router from '@/router'
import { ElMessage } from 'element-plus'
import { DEMO, TOKEN } from '@/store/methodConstant'

let instance = axios.create({
  timeout: 3000,
});

//请求超时时间
instance.defaults.timeout=10000;

//请求拦截器
instance.interceptors.request.use((config =>{
  if (DEMO && (config.method !== 'get' && config.url !== '/api/login' && config.url !== '/api/comment')){
    ElMessage({
      showClose: true,
      message: '演示模式，无法操作',
      type: 'error',
    })
    return false
  }
  //携带令牌
  if (store.getters.token != null){
    config.headers['Authorization'] = `Bearer ${store.getters.token}`
  }
  return config;
}),error => {
  // 对请求错误做些什么
  console.log(error)
  //返回一个拒绝对象
  return Promise.reject(error);
})


//响应拦截器
instance.interceptors.response.use(response =>{
  //是否有刷新令牌返回？
  if (response.headers['refresh_token']){
     store.commit(TOKEN,response.headers['refresh_token'])
  }
  return response
},error => {
  //异常回调
  console.log("http错误码"+error.response.status)
  //403为安全异常，如未登录。登录过期。验证码错误
  if (error.response.status === 403){
    ElMessage({
      showClose: true,
      message: error.response.data.message,
      type: 'error',
    })
    router.push('/login')
  }
  //服务器异常
  if (error.response.status === 500){
    ElMessage({
      showClose: true,
      message: "服务器内部异常",
      type: 'error',
    })
  }
  //业务异常
  if (error.response.status === 400){
    ElMessage({
      showClose: true,
      message: error.response.data.message,
      type: 'error',
    })
  }
  //接口权限不足
  if (error.response.status === 401){
    ElMessage({
      showClose: true,
      message: error.response.data.message,
      type: 'error',
    })
  }
  //网络请求不存在
  if (error.response.status === 404){
    ElMessage({
      showClose: true,
      message: '网络请求不存在',
      type: 'error',
    })
  }
  throw error
})

export default instance
